const mongoose = require('mongoose');
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');

// 定义多媒体文件模型
const mediaFileSchema = new mongoose.Schema({
  _id: { type: String, required: true, unique: true },
  fileId: { type: String, required: true, unique: true },
  filePath: { type: String, required: true },
  fileType: { type: String, required: true, enum: ['image', 'video', 'audio', 'document'] },
  fileSize: { type: Number, required: true },
  fileHash: { type: String, required: true },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

// 生成文件哈希的静态方法
mediaFileSchema.statics.generateFileHash = async function(filePath) {
  return new Promise((resolve, reject) => {
    const hash = crypto.createHash('sha256');
    const stream = fs.createReadStream(filePath);
    
    stream.on('data', data => hash.update(data));
    stream.on('end', () => resolve(hash.digest('hex')));
    stream.on('error', reject);
  });
};

// 生成唯一文件ID的静态方法
mediaFileSchema.statics.generateFileId = function() {
  return crypto.randomBytes(16).toString('hex');
};

// 更新时间的钩子
mediaFileSchema.pre('save', function(next) {
  this.updatedAt = Date.now();
  next();
});

module.exports = mongoose.model('MediaFile', mediaFileSchema);